<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="加油站名称" prop="name" >
        <el-input v-model="queryParams.name" placeholder="请输入加油站名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入联系方式" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="加油站地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入加油站地址" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['yyq:GesStation:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['yyq:GesStation:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['yyq:GesStation:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['yyq:GesStation:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="GesStationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="50" />
      <el-table-column label="加油站名称" align="center" prop="name" />
      <el-table-column label="加油站图片" align="center" prop="img" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="营业时间" align="center" prop="week" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="加油站地址" align="center" prop="address" />
      <el-table-column label="优惠信息" align="center" prop="message" />
      <el-table-column label="删除状态" align="center" prop="deleted">
        <template #default="scope">
          <el-tag v-if="scope.row.deleted === 1" type="danger">禁用</el-tag>
          <el-tag v-else type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="addGesType(scope.row)">汽油类型</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['yyq:GesStation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['yyq:GesStation:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改加油站对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="GesStationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="加油站名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入加油站名称" />
        </el-form-item>
        <el-form-item label="加油站图片" prop="img">
          <image-upload v-model="form.img" />
        </el-form-item>
        <el-form-item label="营业时间" prop="week">
          <el-input v-model="form.week" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="加油站地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入加油站地址" />
        </el-form-item>
        <el-form-item label="优惠信息" prop="message">
          <el-input v-model="form.message" placeholder="请输入优惠信息" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="维度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入维度" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 加油汽油信息 -->
    <el-dialog :title="title2" v-model="open2" width="800px" append-to-body>
      <el-table v-loading="loading" :data="gasStationTypeList">
        <!-- <el-table-column label="加油站名称" align="center">
          <template #default="scope">
            {{ GesStationList.find(item => item.id === scope.row.gasStationId)?.name || scope.row.gasStationId }}
          </template>
        </el-table-column> -->
        <el-table-column label="汽油类型" align="center">
          <template #default="scope">
            {{ CarGesTypeList.find(item => item.id === scope.row.gasTypeId)?.name || scope.row.gasTypeId }}
          </template>
        </el-table-column>
        <el-table-column label="汽油的价格" align="center" prop="price" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate2(scope.row)"
              v-hasPermi="['yyq:gasStationType:edit']">修改价格</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete2(scope.row)"
              v-hasPermi="['yyq:gasStationType:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加汽油类型信息 -->
      <el-button type="primary" plain icon="Plus" @click="gasStationTypeHandleAdd">新增汽油信息</el-button>
    </el-dialog>

    <!-- 添加或修改加油汽油对话框 -->
    <el-dialog :title="title3" v-model="open3" width="500px" append-to-body>
      <el-form :model="formgasStationType" :rules="rules3" ref="gasStationTypeRef" label-width="80px">
        <el-form-item label="汽油类型" prop="gasTypeId" v-if="title3 === '添加汽油类型信息'" >
          <el-select v-model="formgasStationType.gasTypeId" placeholder="请选择汽油类型" clearable filterable>
            <el-option v-for="item in getAvailableGasTypes()" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="汽油价格" prop="price">
          <el-input v-model="formgasStationType.price" placeholder="请输入汽油的价格" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm2">确 定</el-button>
          <el-button @click="cancel2">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="GesStation">
import { listGesStation, getGesStation, delGesStation, addGesStation, updateGesStation } from "@/api/yyq/GesStation"
// 加油站列表
import { listCarGesType } from "@/api/yyq/CarGesType"
// 中间表
import { listGasStationType, getGasStationType, delGasStationType, addGasStationType, updateGasStationType } from "@/api/yyq/gasStationType"

const { proxy } = getCurrentInstance()

const GesStationList = ref([])
const CarGesTypeList = ref([])
const gasStationTypeList = ref([])
const open = ref(false)
const open2 = ref(false)
const open3 = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const title2 = ref("")
const title3 = ref("")



const data = reactive({
  form: {},
  formgasStationType: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    week: null,
    phone: null,
    address: null,
  },
  queryParams2: {
    pageNum: 1,
    pageSize: 9999,
    gasStationId: null,
  },
  rules: {
    name: [
      { required: true, message: "加油站名称不能为空", trigger: "blur" }
    ],
    img: [
      { required: true, message: "加油站图片不能为空", trigger: "blur" }
    ],
    week: [
      { required: true, message: "营业时间不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "联系方式不能为空", trigger: "blur" }
    ],
    address: [
      { required: true, message: "加油站地址不能为空", trigger: "blur" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "维度不能为空", trigger: "blur" }
    ],
  },
  rules3:{
    price: [
      { required: true, message: "汽油价格不能为空", trigger: "blur" },
      { 
        pattern: /^\d+(\.\d{1,2})?$/, 
        message: "请输入正确的价格格式（数字或小数，最多两位小数）", 
        trigger: 'blur' 
      }
    ],
    gasTypeId: [
      { required: true, message: "请选择汽油类型", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules, queryParams2, formgasStationType, rules3} = toRefs(data)



/** 查看汽油*/
function addGesType(row) {
  queryParams2.value.gasStationId = row.id
  getgasStationTypeList()
  open2.value = true
  title2.value = row.name+"---汽油类型"
}

/** 查询加油站列表 */
function getList() {
  loading.value = true
  listGesStation(queryParams.value).then(response => {
    GesStationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 查询汽油种类列表 */
function getListGesType() {
  listCarGesType(queryParams.value).then(response => {
    CarGesTypeList.value = response.rows.filter(item => item.deleted !== 1)
    loading.value = false
  })
}
/** 查询加油站和汽油种类中间列表 */
function getgasStationTypeList() {
  loading.value = true
  listGasStationType(queryParams2.value).then(response => {
    gasStationTypeList.value = response.rows
    loading.value = false
  })
}
/** 新增加油站和汽油种类中间 */
function gasStationTypeHandleAdd() {
  formgasStationType.value = {
    id: null,
    gasStationId: queryParams2.value.gasStationId, // 使用当前查询的加油站ID
    gasTypeId: null,
    price: null,
  }
  open3.value = true
  title3.value = "添加汽油类型信息"
}
function getAvailableGasTypes() {
  // 获取已添加的汽油类型ID
  const addedIds = gasStationTypeList.value.map(item => item.gasTypeId)
  // 过滤出未添加的类型
  return CarGesTypeList.value.filter(item => !addedIds.includes(item.id))
}
// submitForm2 提交表单
function submitForm2() {
  proxy.$refs["gasStationTypeRef"].validate(valid => {
    if (valid) {
      if (formgasStationType.value.id != null) {
        updateGasStationType(formgasStationType.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open3.value = false
          getgasStationTypeList()
        })
      } else {
        addGasStationType(formgasStationType.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open3.value = false
          getgasStationTypeList()
        })
      }
    }
  })
}
function cancel2() {
  open3.value = false
  reset()
}
/** 修改按钮操作 */
function handleUpdate2(row) {
  reset()
  const _id = row.id || ids.value
  getGasStationType(_id).then(response => {
    formgasStationType.value = response.data
    open3.value = true
    title3.value = "修改汽油类型信息"
  })
}
/** 汽油类型删除按钮操作 */
function handleDelete2(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除').then(function() {
    return delGasStationType(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    img: null,
    week: null,
    phone: null,
    address: null,
    message: null,
    longitude: null,
    latitude: null,
    deleted: null,
  }
  proxy.resetForm("GesStationRef")
}

// 表单formgasStationType
function reset2() {
  formgasStationType.value = {
    id: null,
    gasStationId: null,
    gasTypeId: null,
    price: null,
  }
  proxy.resetForm("GesStationTypeRef")
}




/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加加油站"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getGesStation(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改加油站"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["GesStationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGesStation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGesStation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除加油站编号为"' + _ids + '"的数据项？').then(function () {
    return delGesStation(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('yyq/GesStation/export', {
    ...queryParams.value
  }, `GesStation_${new Date().getTime()}.xlsx`)
}

getList()
// 查询汽油类型
getListGesType()
</script>